package com.watson.activity;

import static com.watson.fragment.HomeFragment.U_DEPOT_ID;

import android.app.Dialog;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.watson.Base2Activity;
import com.watson.LoginActivity;
import com.watson.R;
import com.watson.adapter.Details2Adapter;
import com.watson.http.CommonHttpConsts;
import com.watson.http.HttpCallbackData;
import com.watson.http.HttpClient;
import com.watson.utils.DialogUitl;
import com.watson.utils.LogUtils;
import com.watson.utils.SPUtils;
import com.watson.utils.StringUtils;
import com.watson.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Details3Activity extends Base2Activity {
    private TextView tvTitle, tvbillsort, tvTime, tvout_storage, tvStatus;
    private AppCompatButton btnClaim, btnCancellation;
    private NestedScrollView sNestedScrollView;
    private RecyclerView recyclerData;
    private Details2Adapter detailsAdapter;
    private String noId, zt;
    private Map dataList;
    private ArrayList<Map> detailsList;
    private String R_Auth_Code = "";
    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details3);
        statusbar4();
        dataList = new HashMap();
        detailsList = new ArrayList<>();
        noId = getIntent().getStringExtra("no");
        LogUtils.e("TAG", "--------->" + noId);
        zt = getIntent().getStringExtra("zt");
        R_Auth_Code = SPUtils.get(mContext, "auth", "") + "";
        initView();
        initClick();
        get_WMS_WarehouseEntryTaskDetails(noId, zt);
    }

    public void ts_cg() {
        Details3Activity.this.runOnUiThread(() -> {
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
            mediaPlayer = MediaPlayer.create(mContext, R.raw.ts_cg);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.start();
        });
    }

    public void ts_cw() {
        Details3Activity.this.runOnUiThread(() -> {
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
            mediaPlayer = MediaPlayer.create(mContext, R.raw.ts_cw);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.start();
        });
    }

    private void initClick() {
        findViewById(R.id.imgBack).setOnClickListener(v -> {
            finish();
        });

        btnCancellation.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            exitDialog(0);
        });

        btnClaim.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            if (!dataList.isEmpty()) {
                exitDialog(5);
            }
        });
    }

    private void add_WMS_WarehouseEntryTask(String no, String sn) {
        Map data = new HashMap();
        data.put("no", noId);
        data.put("sn", sn);
        data.put("taskrecipient", SPUtils.get(mContext, "U_Name", "") + "");
        data.put("taskrecipientid", SPUtils.get(mContext, "U_Id", "") + "");//任务领取人id
        data.put("wh", U_DEPOT_ID + "");//作业仓库
        if (R_Auth_Code.contains("WMS_IN_SCAN_ClAIMTICKET")) {
            data.put("authcode", "WMS_IN_SCAN_ClAIMTICKET");
        } else {
            data.put("authcode", "");
        }
        String datStr = new Gson().toJson(data);
        HttpClient.getInstance().postData(CommonHttpConsts.add_WMS_WarehouseEntryTask, "add_WMS_WarehouseEntryTask")
                .headers("token", SPUtils.get(mContext, "token", "") + "")
                .upJson(datStr)
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        ToastUtil.show(msg);
                        if (code == 1001) {
                            ts_cg();
                            Intent data = new Intent();
                            data.putExtra("name", true);
                            setResult(RESULT_OK, data);
                            finish();
                        } else {
                            ts_cw();
                        }
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }
                });
    }

    public void exitDialog(int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_exit, null);
        TextView tvDelete = v.findViewById(R.id.tvDelete);
        TextView tvName = v.findViewById(R.id.tvName);
        TextView tvSave = v.findViewById(R.id.tvSave);
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
        if (type == 0) {
            tvName.setText("确认作废订单吗");
        }
        if (type == 5) {
            tvName.setText("确认领单吗");
        }
        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvDelete.setOnClickListener(v1 -> dialog.dismiss());

        tvSave.setOnClickListener(view -> {
            if (type == 1 || type == 0) {
                delete_WMS_WarehouseEntryTask(type);
            }
            if (type == 5) {
                add_WMS_WarehouseEntryTask(dataList.get("no") + "", StringUtils.getDeviceSN(mContext));
            }
            dialog.dismiss();
        });
    }

    private void initView() {
        tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText("验单详情");
        tvStatus = findViewById(R.id.tvStatus);
        recyclerData = findViewById(R.id.recyclerData);
        recyclerData.setLayoutManager(new LinearLayoutManager(mContext));
        detailsAdapter = new Details2Adapter(mContext, detailsList);
        recyclerData.setAdapter(detailsAdapter);
        detailsAdapter.setItemClickListener(new Details2Adapter.ItemClickListener() {
            @Override
            public void onClick(int position, ArrayList<Map> mList) {

            }

            @Override
            public void onBClick(int position) {
            }
        });
        tvbillsort = findViewById(R.id.tvbillsort);
        tvout_storage = findViewById(R.id.tvout_storage);
        tvTime = findViewById(R.id.tvTime);
        btnClaim = findViewById(R.id.btnClaim);

        btnCancellation = findViewById(R.id.btnCancellation);
        sNestedScrollView = findViewById(R.id.sNestedScrollView);
        sNestedScrollView.post(() -> sNestedScrollView.fullScroll(ScrollView.FOCUS_UP));
    }

    private void setView(Map map) {
        tvbillsort.setText(map.get("billsort") + "");
        tvout_storage.setText(StringUtils.isEmpty(map.get("in_storage") + "") ? "" : map.get("in_storage") + "");
        tvTime.setText(map.get("lastbillsort") + "-" + map.get("lastbillno"));
        btnClaim.setVisibility(View.GONE);
        btnCancellation.setVisibility(View.GONE);
        String taskrecipient = map.get("taskrecipient") + "";
        if (!StringUtils.isEmpty(taskrecipient)) {
            tvTitle.setText("详情(" + taskrecipient.trim() + ")");
        }
        // "taskstatus": "未领单", "验单中",
        String taskstatus = map.get("taskstatus") + "";//单据状态
        if (StringUtils.isEmpty(taskstatus)) {
            taskstatus = "";
        }
        tvStatus.setText(taskstatus);
        //任务的状态：进行中  已完成   暂存  作废（作废单据不会返回给app端）
        if (taskstatus.equals("未领单")) {
            tvStatus.setTextColor(mContext.getResources().getColor(R.color.status1));
        }
        if (taskstatus.equals("验单中")) {
            tvStatus.setTextColor(mContext.getResources().getColor(R.color.status2));
        }
        if (taskstatus.equals("作废")) {
            tvStatus.setTextColor(mContext.getResources().getColor(R.color.status3));
        }

        LogUtils.e("TAG", "R_Auth_Code:" + R_Auth_Code.toString());
        if (R_Auth_Code.contains("ADD_WarehouseEntryTask") && taskstatus.equals("未领单")) {
            //领单
            btnClaim.setVisibility(View.VISIBLE);
        } else {
            btnClaim.setVisibility(View.GONE);
        }

//        if (R_Auth_Code.contains("DEL_WarehouseEntryTask") && !taskstatus.equals("作废")) {
//            //作废
//            btnCancellation.setVisibility(View.VISIBLE);
//        } else {
//            btnCancellation.setVisibility(View.GONE);
//        }
    }


    private void get_WMS_WarehouseEntryTaskDetails(String id, String zt) {
        HttpClient.getInstance().getData(CommonHttpConsts.get_WMS_WarehouseEntryTaskDetails, "get_WMS_WarehouseEntryTaskDetails")//
                .headers("token", SPUtils.get(mContext, "token", "") + "").params("no", id + "")//单号
//                .params("zt", zt)//单据归属
                .execute(new HttpCallbackData() {
                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 1001 && !StringUtils.isEmpty(info)) {
                            dataList = JSON.parseObject(info, Map.class);
                            LogUtils.e("TAG", "dataList:" + dataList.toString());
                            if (!dataList.isEmpty()) {
                                if (StringUtils.isEmpty(dataList.get("details") + "")) {
                                    ToastUtil.show("数据异常，请重试");
                                    return;
                                }
                                ArrayList<Map> list = new ArrayList<>();
                                detailsList = (ArrayList<Map>) JSON.parseArray(dataList.get("details") + "", Map.class);
                                LogUtils.e("TAG", "dataList:" + dataList.toString());
                                detailsAdapter.setData(detailsList);
                                detailsAdapter.setBillstatus(dataList.get("taskstatus") + "", dataList.get("taskrecipientid") + "");

                                setView(dataList);
                            }
                        } else {
                            ToastUtil.show(msg);
                        }
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }
                });
    }

    private void delete_WMS_WarehouseEntryTask(int type) {
        Map data = new HashMap();
        data.put("no", noId);
//        data.put("type", type);//0作废，1撤单
        String datStr = new Gson().toJson(data);
        HttpClient.getInstance().getData(CommonHttpConsts.delete_WMS_WarehouseEntryTask, "delete_WMS_WarehouseEntryTask").headers("token", SPUtils.get(mContext, "token", "") + "").params("no", noId).execute(new HttpCallbackData() {

            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);
                ToastUtil.show(msg);
                if (code == 1001) {
                    ts_cg();
                    Intent data = new Intent();
                    data.putExtra("name", true);
                    setResult(RESULT_OK, data);
                    finish();
                } else {
                    ts_cw();
                }
            }

            @Override
            public boolean showLoadingDialog() {
                return true;
            }

            @Override
            public Dialog createLoadingDialog() {
                return DialogUitl.loginAuthDialog(mContext);
            }
        });
    }
}
